var allowedImageExt = [
  'jpg',
  'jpeg',
];

var ajax_options = {
  //target:        '#output2',   // target element(s) to be updated with server response
  beforeSubmit:  showRequest,  // pre-submit callback
  success:       showResponse,  // post-submit callback
  dataType:  'json'        // 'xml', 'script', or 'json' (expected server response type)

  // other available options:
  //url:       url         // override for form's 'action' attribute
  //type:      type        // 'get' or 'post', override for form's 'method' attribute
  //clearForm: true        // clear all form fields after successful submit
  //resetForm: true        // reset the form after successful submit

  // jQuery.ajax options can be used here too, for example:
  //timeout:   3000
};

function clearMessage() {
  jQuery('#winMessage').remove();
}

function displayMessage(type, msg) {
  clearMessage();
  var msghtml = '<div id="winMessage" class="message ' + type + '">' + msg + '</div>';
  jQuery(msghtml).insertBefore('#uploadimageform');

  return false;
}

function checkValidImageFile(filename) {
  var indx = filename.lastIndexOf('.');
  if (indx != -1) {
    var ext = filename.substr(indx + 1).toLowerCase();
    if (in_array(ext, allowedImageExt)) {
      return true;
    }
  }
  return false;
}

// pre-submit callback
function showRequest(formData, jqForm, options) {
  generateJSONRequest();

  /*
  // formData is an array; here we use jQuery.param to convert it to a string to display it
  // but the form plugin does this for you automatically when it submits the data
  var queryString = jQuery.param(formData);

  // jqForm is a jQuery object encapsulating the form element.  To access the
  // DOM element for the form do this:
  // var formElement = jqForm[0];

  alert('About to submit: \n\n' + queryString);
  */

  // here we could return false to prevent the form from being submitted;
  // returning anything other than false will allow the form submit to continue
  return true;
}

// post-submit callback
function showResponse(responseJSON, statusText)  {
  if (statusText == 'success') {
    if (responseJSON.error == 1) {
      //return displayMessage('error', responseJSON.msg);
      alert(responseJSON.msg);
    } else {
      url = window.location.href;
      window.location.replace(url);
    }
  } else {
    //return displayMessage('error', statusText);
    alert(statusText);
  }
  return false;
}

function generateJSONRequest() {
  var data = new Object();

  data.action = 'uploadImage';
  var params = new Object();

  params.fileElem = 'imgfile';
  params.observation_id = jQuery('#observation_id').val();
  params.copyright_text = jQuery('#imgCopyright').val();

  data.params = params;

  var request_str = JSON.stringify(data);

  jQuery('#request').val(request_str);
}

function submitImageUploadForm() {
  clearMessage();

  var atlst1FileSelected = false;
  //var flname = jQuery('#imgfile').val();
  var $imgfile = jQuery('input[name=imgfile[]]');
  var len = $imgfile.length;
  for (var i = 0; i < len; i++) {
    var flname = $imgfile[i].value;
    if (flname != '') {
      if (!checkValidImageFile(flname)) {
        var msg = 'Only image files with following extensions are allowed.';
        msg += '<ul>';
        for (var i = 0; i < allowedImageExt.length; i++) {
          msg += '<li>' + allowedImageExt[i];
        }
        msg += '</ul>';
        return displayMessage('error', msg);
      }
      atlst1FileSelected = true;
    }
  }
  if (!atlst1FileSelected) {
    return displayMessage('error', 'Please select a file to upload.');
  }

  jQuery(this).ajaxSubmit(ajax_options);

  return false;
}

jQuery(document).ready(function(){
  var $dialog = jQuery("#divImageUpload");
  $dialog.dialog({
    autoOpen: false,
    modal: true,
    minHeight: 150,
    minWidth: 400,
  });

  jQuery('#btnImageUpload').click(function() {
		$dialog.dialog('open');
	});

  // bind to the form's submit event
  jQuery('#uploadimageform').submit(submitImageUploadForm);
});